<template>
  <!-- 顶部导航 -->
  <div class="header">
    <div class="nav-links">
      <button @click="handleLogout" class="logout-btn">登出</button>
    </div>
  </div>

  <!-- 主体内容 -->
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <div class="system-title">管理系统</div>
      <ul class="menu">
        <li><router-link to="/manager" class="menu-link">首页</router-link></li>
        <li class="parent-menu" @click="toggleMenu('user')">
          <span class="menu-item">
            <span>用户管理</span>
            <span class="toggle-icon">{{ expanded.user ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.user" class="submenu">
            <li><router-link to="/userlist" class="submenu-link">用户列表</router-link></li>
            <li><router-link to="/adminlist" class="submenu-link">管理员列表</router-link></li>
          </ul>
        </li>
        <li class="parent-menu" @click="toggleMenu('product')">
          <span class="menu-item">
            <span>商品管理</span>
            <span class="toggle-icon">{{ expanded.product ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.product" class="submenu">
            <li><router-link to="/productlist" class="submenu-link">商品列表</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容（商品列表） -->
    <div class="content">
      <div class="content-header">
        <div class="search-bar">
          <input
            type="text"
            placeholder="输入商品名或编号查询"
            v-model="searchKeyword"
            @focus="onFocus"
            @keyup.enter="handleSearch"
          />
          <button @click="handleSearch" class="btn btn-primary" style="margin-left: 10px;">查询</button>
        </div>
        <div class="btn-group">
          <button class="btn-add" @click="showAddModal = true">增加</button>
        </div>
      </div>

      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>商品名称</th>
            <th>商品编号</th>
            <th>价格</th>
            <th>销量</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="loading">
          <tr>
            <td colspan="7" class="table-tip">正在加载，请稍候...</td>
          </tr>
        </tbody>
        <tbody v-else-if="errorMessage">
          <tr>
            <td colspan="7" class="table-tip error">{{ errorMessage }}</td>
          </tr>
        </tbody>
        <tbody v-else-if="filteredProducts.length === 0">
          <tr>
            <td colspan="7" class="table-tip">暂无商品数据</td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr v-for="(item, index) in filteredProducts" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.code }}</td>
            <td>{{ item.price ?? '-' }}</td>
            <td>{{ item.sales }}</td>
            <td>{{ item.status }}</td>
            <td>
              <button @click="openEditModal(item)" class="btn btn-sm btn-warning">修改</button>
              <button @click="openDeleteModal(item)" class="btn btn-sm btn-danger">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="showAddModal" class="modal-overlay">
        <div class="modal-content">
          <h3>新增商品</h3>
          <div class="form-group">
            <label>商品名称：</label>
            <input v-model="newProduct.name" placeholder="请输入商品名称" required />
          </div>
          <div class="form-group">
            <label>价格：</label>
            <input v-model.number="newProduct.price" type="number" placeholder="请输入价格" required />
          </div>
          <div class="form-group">
            <label>销量：</label>
            <input v-model.number="newProduct.sales" type="number" placeholder="请输入销量" required />
          </div>
          <div class="form-group">
            <label>状态：</label>
            <select v-model="newProduct.status">
              <option value="正常销售">正常销售</option>
              <option value="停售">停售</option>
              <option value="预售">预售</option>
            </select>
          </div>
          <div class="modal-footer">
            <button @click="cancelAdd" class="btn btn-secondary">取消</button>
            <button @click="confirmAdd" class="btn btn-primary" :disabled="!isValid">确认</button>
          </div>
        </div>
      </div>
      <!-- 编辑商品弹窗 -->
      <div v-if="showEditModal" class="modal-overlay">
        <div class="modal-content">
          <h3>编辑商品</h3>
          <div class="form-group">
            <label>商品名称：</label>
            <input v-model="newProduct.name" placeholder="请输入商品名称" required />
          </div>
          <div class="form-group">
            <label>价格：</label>
            <input v-model.number="newProduct.price" type="number" placeholder="请输入价格" required />
          </div>
          <div class="form-group">
            <label>销量：</label>
            <input v-model.number="newProduct.sales" type="number" placeholder="请输入销量" required />
          </div>
          <div class="form-group">
            <label>状态：</label>
            <select v-model="newProduct.status">
              <option value="正常销售">正常销售</option>
              <option value="停售">停售</option>
              <option value="预售">预售</option>
            </select>
          </div>
          <div class="modal-footer">
            <button @click="showEditModal = false" class="btn btn-secondary">取消</button>
            <button @click="confirmEdit" class="btn btn-primary">确认</button>
          </div>
        </div>
      </div>
      <div v-if="showDeleteModal" class="modal-overlay">
        <div class="modal-content" style="width: 350px;">
          <h3>删除确认</h3>
          <p>确定要删除商品 "<strong>{{ itemToDelete?.name }}</strong>" 吗？此操作不可恢复！</p>
          <div class="modal-footer">
            <button @click="showDeleteModal = false" class="btn btn-secondary">取消</button>
            <button @click="confirmDelete" class="btn btn-danger">确定删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api'

// 商品数据
const products = ref([])

// 搜索关键词
const searchKeyword = ref('')

// 当前选中的商品（用于修改/删除）
const editingItem = ref(null)

// 弹窗控制
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const itemToDelete = ref(null)

const loading = ref(false)
const errorMessage = ref('')

// 新商品表单数据
const newProduct = ref({
  name: '',
  price: 0,
  sales: 0, // 对应销量 salesQuantity
  status: '正常销售',
  pictureUrl: '',
  link: '',
  type: '',
  description: ''
})

const router = useRouter()
const expanded = reactive({ user: false, product: true }) // 默认展开商品管理

const fetchProducts = async () => {
  loading.value = true
  errorMessage.value = ''
  try {
    const params = {}
    const keyword = searchKeyword.value.trim()
    if (keyword) {
      params.keyword = keyword
    }
    const res = await api.getProductList(params)
    const rows = res?.data?.products || res?.data || []
    products.value = rows.map(p => ({
      id: p.productId,
      name: p.productName,
      code: p.productId,
      price: p.price,
      sales: p.salesQuantity ?? 0,
      status: p.status || '正常销售',
      pictureUrl: p.imageUrl,
      link: p.productUrl,
      description: p.description
    }))
  } catch (error) {
    console.error('获取商品列表失败:', error)
    errorMessage.value = error.message || '获取商品列表失败，请稍后重试'
    products.value = []
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  fetchProducts()
}

// 过滤后的商品列表（前端过滤暂不需要，因为后端已搜索，但为了保持逻辑一致，这里直接返回 products）
const filteredProducts = computed(() => {
  return products.value
})

// 计算是否表单有效
const isValid = computed(() => {
  return (
    newProduct.value.name.trim() &&
    newProduct.value.price > 0
  )
})

const onFocus = (e) => {
  e.target.select()
}

const cancelAdd = () => {
  showAddModal.value = false
  resetNewProduct()
}

const resetNewProduct = () => {
  newProduct.value = {
    name: '',
    price: 0,
    sales: 0,
    status: '正常销售',
    pictureUrl: '',
    link: '',
    type: '',
    description: ''
  }
}

const confirmAdd = async () => {
  if (!isValid.value) return

  try {
    await api.addProduct({
      productName: newProduct.value.name,
      price: newProduct.value.price,
      salesQuantity: newProduct.value.sales,
      pictureUrl: newProduct.value.pictureUrl || 'default.jpg', // 必填或默认
      describe: newProduct.value.description,
      type: '未分类', // 默认
      platformId: 1 // 默认淘宝
    })
    
    showAddModal.value = false
    resetNewProduct()
    fetchProducts()
    alert('添加成功')
  } catch (error) {
    alert(error.message || '添加失败')
  }
}

const openEditModal = (item) => {
  newProduct.value = {
    name: item.name,
    price: item.price,
    sales: item.sales,
    status: item.status,
    description: item.description,
    pictureUrl: item.pictureUrl
  }
  editingItem.value = item
  showEditModal.value = true
}

const confirmEdit = async () => {
  if (!newProduct.value.name.trim() || newProduct.value.price <= 0) {
    alert('请填写正确的商品信息！')
    return
  }

  try {
    await api.updateProduct(editingItem.value.id, {
      productName: newProduct.value.name,
      price: newProduct.value.price,
      salesQuantity: newProduct.value.sales,
      describe: newProduct.value.description
    })
    
    showEditModal.value = false
    editingItem.value = null
    resetNewProduct()
    fetchProducts()
    alert('修改成功')
  } catch (error) {
    alert(error.message || '修改失败')
  }
}

const openDeleteModal = (item) => {
  itemToDelete.value = item
  showDeleteModal.value = true
}

const confirmDelete = async () => {
  if (itemToDelete.value) {
    try {
      await api.deleteProduct(itemToDelete.value.id)
      showDeleteModal.value = false
      itemToDelete.value = null
      fetchProducts()
      alert('删除成功')
    } catch (error) {
      alert(error.message || '删除失败')
    }
  }
}

const toggleMenu = (key) => {
  expanded[key] = !expanded[key]
}

const handleLogout = () => {
  api.logout().finally(() => {
    router.push('/admin-login')
  })
}

onMounted(() => {
  fetchProducts()
})

</script>

<style scoped>
/* ========== 布局基础 ========== */
@import '@/CSS/ManagerPublicCss.css';
/* ========== 右侧内容 ========== */
@import '@/CSS/ManagerPageProductList.css';
</style>